package cn.dc406.labc406mgr.controller;

import cn.dc406.labc406mgr.entity.User;
import cn.dc406.labc406mgr.mapper.LoginRegMapper;
import org.apache.commons.lang.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

@RestController
public class LoginRegController {

    @Autowired(required = false)
    LoginRegMapper loginRegMapper;

    @CrossOrigin
    @RequestMapping("/login")
    int login(@RequestBody User user, HttpSession session)
    {
        User user1=loginRegMapper.selectUserByUsername(user.getUsername());
        if(user1==null)return 1;//用户名不存在
        else{
            if(user.getPassword().equals(user1.getPassword()))
            {
                session.setAttribute("user",user1);
                session.setMaxInactiveInterval(60*60);//1小时失效
                System.out.println("loginsessionuser="+(User)session.getAttribute("user"));
                if(user1.getAuth().equals("1"))
                {
                    return 999;//管理员
                }else{
                    return 2;//登录成功
                }

            }else{
                return 3;//密码错误
            }
        }
    }

    @CrossOrigin
    @RequestMapping("/register")
    int register(@RequestBody User user)
    {
        if(user.getCode().equals("406406406"))//邀请码匹配上
        {
            try {
                int res=loginRegMapper.insertUser(user);
            }
           catch (Exception e)
           {
               return 0;//用户名重复
           }
            return 1;//注册成功
        }
        else return 2;//邀请码错误
    }

    @CrossOrigin
    @RequestMapping("/logout")
    void logout(HttpSession session)
    {
        System.out.println("logout");
        session.removeAttribute("user");
    }

    @CrossOrigin
    @RequestMapping("/getLoginInfo")
    User getLoginInfo(HttpSession session)
    {
        System.out.println("LoginUser="+(User)session.getAttribute("user"));
        return (User)session.getAttribute("user");
    }
}
